package io.dirac.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.dirac.entity.Product;
import io.dirac.result.Result;
import io.dirac.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Dirac
 * @since 2021-04-11
 */
@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private ProductService productService;

    @GetMapping("/{id}")
    public Result getById(@PathVariable(value = "id") Long id) {
        return Result.success(productService.getById(id));
    }

    @GetMapping("/all")
    public Result getAll() {
        return Result.success(productService.list());
    }

    @GetMapping("/cheapest")
    public Result getCheapest() {
        Page<Product> page = new Page<>(1, 10);
        QueryWrapper<Product> wrapper = new QueryWrapper<>();
        wrapper.orderByAsc("price");
        return Result.success(productService.page(page, wrapper).getRecords());
    }

    @GetMapping("/hottest")
    public Result getHottest() {
        return Result.success( productService.getSales());
    }

    @GetMapping("/for_species/{species_id}")
    public Result getBySpeciesId(@PathVariable(value = "species_id") Long species_id) {
        QueryWrapper<Product> wrapper = new QueryWrapper<>();
        wrapper.eq("pc_id", species_id);
        return Result.success(productService.list(wrapper));
    }

    @GetMapping("/for_brand/{brand_id}")
    public Result getByBrandId(@PathVariable(value = "brand_id") Long brand_id) {
        QueryWrapper<Product> wrapper = new QueryWrapper<>();
        wrapper.eq("pc_child_id", brand_id);
        return Result.success(productService.list(wrapper));
    }

    @PostMapping("/add")
    public Result addProduct(@Validated @RequestBody Product product) {
        productService.save(product);
        return Result.success(null);
    }
}
